package dao

import (
	"errors"

	"github.com/google/uuid"

	"io"
	"net"
	__ "order-srv/basic/proto"
	"order-srv/handler/models"
	"order-srv/pkg"
	"time"
)

// 创建订单 - 更新为匹配新的proto定义
func CreateOrder(in *__.CreateOrderReq) (models.Order, error) {
	// 1. 校验用户是否存在
	var user models.User
	user.Id = uint(in.UserId)
	if err := user.GetUserExistence(); err != nil {
		return models.Order{}, err
	}
	if user.UStatus == 2 {
		return models.Order{}, errors.New("该用户被冻结")
	}

	// 2. 创建订单
	order := models.Order{
		OrderNo:     "JD" + time.Now().Format("20060102150405") + uuid.NewString()[:8],
		AddressId:   in.AddressId,
		UserId:      in.UserId,
		GoodsId:     in.GoodsId,
		GoodsNum:    in.GoodsNum,
		GoodsName:   in.GoodsName,
		GoodsPrice:  in.GoodsPrice, // 修复：直接使用int64类型，不需要转换
		OrderNum:    in.OrderNum,
		OrderPrice:  float64(in.OrderPrice),
		PayCType:    in.PayCType,
		PayStatus:   in.PayStatus,
		OrderStatus: in.OrderStatus,
	}

	// 3. 保存订单
	err := order.Create()
	if err != nil {
		pkg.Error("创建订单失败: " + err.Error())
		return models.Order{}, err
	}
	return order, nil
}

// 查询订单详情 - 更新为匹配新的proto定义
func DetailOrder(in *__.DetailOrderReq) (models.Order, error) {
	order := models.Order{
		Id: uint64(in.Id),
	}
	err := order.Detail()
	if err != nil {

		return order, err

	}
	return order, nil
}

// 展示订单列表 - 更新为匹配新的proto定义
func ListOrder(in *__.ListOrderReq) (error, []*__.ListGoods) {
	order := models.Order{
		GoodsName: in.GoodsName,
	}

	// 获取分页数据
	page, err := order.ListPage(int(in.Page), int(in.PageSize))
	if err != nil {
		pkg.Error("获取订单列表失败: " + err.Error())
		return err, nil
	}

	// 转换为proto消息类型
	var list []*__.ListGoods
	for _, o := range page {
		list = append(list, &__.ListGoods{
			Id:          o.Id,
			OrderNo:     o.OrderNo,
			AddressId:   o.AddressId,
			UserId:      o.UserId,
			GoodsId:     o.GoodsId,
			GoodsNum:    o.GoodsNum,
			GoodsName:   o.GoodsName,
			GoodsPrice:  o.GoodsPrice,
			OrderNum:    o.OrderNum,
			OrderPrice:  float32(o.OrderPrice),
			PayCType:    o.PayCType,
			PayStatus:   o.PayStatus,
			OrderStatus: o.OrderStatus,
			CreatedAt:   o.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:   o.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return nil, list
}

// 删除订单 - 更新为匹配新的proto定义
func DelOrder(in *__.DelOrderReq) error {
	order := models.Order{
		Id: in.Id,
	}

	err := order.DelOrder()
	if err != nil {
		return errors.New("删除订单失败: " + err.Error())

	}
	return nil
}

// 修改订单 - 更新为匹配新的proto定义
func UpdateOrder(in *__.UpdateOrderReq) (models.Order, error) {
	order := models.Order{
		Id:          in.Id,
		AddressId:   in.AddressId,
		GoodsId:     in.GoodsId,
		GoodsNum:    in.GoodsNum,
		PayCType:    in.PayCType,
		PayStatus:   in.PayStatus,
		OrderStatus: in.OrderStatus,
	}
	err := order.Update()
	if err != nil {
		pkg.Error("修改订单信息失败: " + err.Error())
		return models.Order{}, err
	}
	if order.PayStatus == 1 {
		GetDistributionUpTwoUserId(in)
	}
	return order, nil
}

// 监听模式
func ListenOrder(in *__.ListenOrderReq) {
	var addr string
	lis, _ := net.Listen("tcp", addr) // 1. 监听端口
	for {                             // 2. 死循环接收
		conn, _ := lis.Accept() // 3. 等待连接
		go func(c net.Conn) {   // 4. 开 goroutine 并发处理
			io.Copy(c, c) // 5. 回显数据
			c.Close()     // 6. 关闭连接
		}(conn)
	}
}

// 创建售后
func AddSales(in *__.CreateSalesReq) (*models.Order, error) {
	var order models.Order
	if err := order.GetOrderById(int(in.OrderId)); err != nil {
		return nil, errors.New("查询订单失败")
	}
	if order.Id == 0 {
		return nil, errors.New("订单不存在")
	}
	if order.UserId != int32(in.UserId) {
		return nil, errors.New("订单不属于该用户")
	}
	if order.PayStatus == 2 {
		return nil, errors.New("订单已支付,可以售后")
	}
	if int64(in.SalesPrice) > order.GoodsPrice {
		return nil, errors.New("退款金额不能大于订单金额")
	}
	order.SalesPrice = in.SalesPrice
	order.Cause = in.Cause
	order.SalesImg = in.SalesImg
	order.Status = 1
	order.SalesStatus = 1
	order.ShopStatus = 2
	order.ShopType = 1
	if err := order.Update(); err != nil {
		return nil, errors.New("更新订单失败")
	}
	return &order, nil
}
